﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MyFramework.Helpers
{
    /// <summary>
    /// Screen shot helpers
    /// </summary>
    public static class ScreenshotHelper
    {

        /// <summary>
        /// Gets the JPG image.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="scale">The scale.</param>
        /// <param name="quality">The quality.</param>
        /// <returns></returns>
        public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
        {
            if (source != null)
            {


                double actualHeight = source.RenderSize.Height;
                double actualWidth = source.RenderSize.Width;

                double renderHeight = actualHeight * scale;
                double renderWidth = actualWidth * scale;
                if (renderHeight > 0 && renderWidth > 0)
                {


                    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
                    VisualBrush sourceBrush = new VisualBrush(source);

                    DrawingVisual drawingVisual = new DrawingVisual();
                    DrawingContext drawingContext = drawingVisual.RenderOpen();

                    using (drawingContext)
                    {
                        drawingContext.PushTransform(new ScaleTransform(scale, scale));
                        drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
                    }
                    renderTarget.Render(drawingVisual);

                    JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
                    jpgEncoder.QualityLevel = quality;
                    jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

                    Byte[] _imageArray;

                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        jpgEncoder.Save(outputStream);
                        _imageArray = outputStream.ToArray();
                    }

                    return _imageArray;
                }
                else
                {
                    return new byte[] { };
                }
            }
            else
            {
                return new byte[] { };
            }
        }
    }
}
